package com.atguigu.gmall.activity.controller;

import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.activity.util.CacheHelper;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.activity.OrderRecode;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.activity.UserRecode;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author atguigu-mqx
 */
@RestController
@RequestMapping("/api/activity/seckill")
public class SeckillGoodsApiController {

    @Autowired
    private SeckillGoodsService seckillGoodsService;

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderFeignClient orderFeignClient;


    //  /api/activity/seckill/findAll
    @GetMapping("findAll")
    public Result findAll() {
        //  调用服务层方法
        List<SeckillGoods> seckillGoodsList = seckillGoodsService.findAll();

        return Result.ok(seckillGoodsList);
    }

    //  /api/activity/seckill/getSeckillGoods/{skuId}
    @GetMapping("getSeckillGoods/{skuId}")
    public Result getSeckillGoods(@PathVariable Long skuId) {
        //  根据skuId 获取到单个秒杀对象
        SeckillGoods seckillGoods = this.seckillGoodsService.getSeckillGoods(skuId);

        return Result.ok(seckillGoods);
    }

    //  http://api.gmall.com/api/activity/seckill/auth/getSeckillSkuIdStr/22
    @GetMapping("auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable Long skuId, HttpServletRequest request) {
        //  生成下单码，放入result 对象中.使用userId生成下单码。 对这个userId 进行使用md5加密就行了.
        String userId = AuthContextHolder.getUserId(request);

        //  判断当前商品是否正在参与秒杀活动！
        SeckillGoods seckillGoods = this.seckillGoodsService.getSeckillGoods(skuId);
        //  判断
        if (seckillGoods != null) {
            //  判断时间：当前系统时间必须在秒杀开始之后，结束之前！
            if (DateUtil.dateCompare(seckillGoods.getStartTime(), new Date())
                    && DateUtil.dateCompare(new Date(), seckillGoods.getEndTime())) {
                String skuIdStr = MD5.encrypt(userId);
                //  返回数据.
                return Result.ok(skuIdStr);
            }
        }
        return Result.fail().message("生成下单码失败");
    }

    //  下单控制器：/api/activity/seckill/auth/seckillOrder/{skuId}?skuIdStr=skuIdStr
    @PostMapping("auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable Long skuId, HttpServletRequest request) {
        //  获取下单码.
        String skuIdStr = request.getParameter("skuIdStr");
        //  需要与userId 进行md5加密的数据进行匹配.
        String userId = AuthContextHolder.getUserId(request);
        //  判断数据.
        if (!skuIdStr.equals(MD5.encrypt(userId))) {
            return Result.fail().message("校验下单码失败.");
        }
        //  校验状态位： skuId:1  skuId:0
        String status = (String) CacheHelper.get(skuId.toString());
        if ("0".equals(status)) {
            //  售罄
//            return Result.build(null, ResultCodeEnum.SECKILL_FINISH);
            return Result.fail().message("商品已售罄.");
        } else if (StringUtils.isEmpty(status)) {
            //  非法秒杀.
            return Result.fail().message("非法秒杀.");
        } else {
            //  可以抢购.  谁秒杀了哪个商品.
            UserRecode userRecode = new UserRecode();
            userRecode.setUserId(userId);
            userRecode.setSkuId(skuId);

            //  发送到队列.
            this.rabbitService.sendMsg(MqConst.EXCHANGE_DIRECT_SECKILL_USER, MqConst.ROUTING_SECKILL_USER, userRecode);
            //  表示下单成功.
            return Result.ok();
        }
    }

    //  检查抢购状态控制器.
    @GetMapping("auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable Long skuId, HttpServletRequest request) {
        //  业务逻辑是什么!

        //  获取到用户Id
        String userId = AuthContextHolder.getUserId(request);
        //  服务层调用方法

        return this.seckillGoodsService.checkOrder(skuId, userId);
    }

    //  秒杀订单页面控制器.
    @GetMapping("/auth/trade")
    public Result seckillTrade(HttpServletRequest request){
        //  声明一个map 集合
        HashMap<String, Object> map = new HashMap<>();
        //  获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        //  存储用户收货地址列表 userAddressList，送货清单 detailArrayList， totalAmount totalNum
        List<UserAddress> userAddressList = this.userFeignClient.findUserAddressListByUserId(userId);

        //  送货清单：
        OrderRecode orderRecode = (OrderRecode) this.redisTemplate.opsForHash().get(RedisConst.SECKILL_ORDERS, userId);

        //  获取到秒杀商品了.
        if (orderRecode==null){
            return Result.fail().message("获取送货清单失败");
        }
        SeckillGoods seckillGoods = orderRecode.getSeckillGoods();

        //  创建一个订单明细
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setSkuId(seckillGoods.getSkuId());
        //  注意：秒杀个数，是由orderRecode决定的。
        orderDetail.setSkuNum(orderRecode.getNum());
        orderDetail.setSkuName(seckillGoods.getSkuName());
        orderDetail.setOrderPrice(seckillGoods.getCostPrice());
        orderDetail.setImgUrl(seckillGoods.getSkuDefaultImg());

        List<OrderDetail> detailArrayList = new ArrayList<>();
        detailArrayList.add(orderDetail);
        map.put("userAddressList",userAddressList);
        map.put("detailArrayList",detailArrayList);
        map.put("totalAmount",seckillGoods.getCostPrice());
        map.put("totalNum",orderRecode.getNum());
        //  默认返回成功.
        return Result.ok(map);
    }

    //  秒杀提交订单。
    @PostMapping("auth/submitOrder")
    public Result seckillSubmitOrder(@RequestBody OrderInfo orderInfo,HttpServletRequest request){
        //  保存订单.
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.parseLong(userId));

        Long orderId = this.orderFeignClient.submitOrder(orderInfo);

        //  判断
        if (orderId==null){
            return Result.fail().message("保存订单失败.");
        }

        //  需要删除预下单记录. hdel key field;
        this.redisTemplate.opsForHash().delete(RedisConst.SECKILL_ORDERS,userId);

        //  将真正下单的记录保存到缓存中.
        this.redisTemplate.opsForHash().put(RedisConst.SECKILL_ORDERS_USERS,userId,orderId.toString());

        // 返回订单Id
        return Result.ok(orderId);
    }
}
